package com.edu.tool.controller.login;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.tool.annotation.NotCheckToken;
import com.edu.tool.bean.user.*;
import com.edu.tool.constant.MsgConstant;
import com.edu.tool.mapper.conf.SysTenantDictConfMapper;
import com.edu.tool.mapper.links.user.SysEmpResponsiblityMapper;
import com.edu.tool.mapper.user.*;
import com.edu.tool.service.sms.SysSmsService;
import com.edu.tool.service.user.SysCaptchaService;
import com.edu.tool.service.user.SysLoginTokenService;
import com.edu.tool.service.user.SysTenantService;
import com.edu.tool.util.IpUtil;
import com.edu.tool.util.MsgUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping(value = "/api/v1")
@RestController
@Api(value="登陆接口")
public class SysLoginController {

    @Autowired
    private SysLoginTokenService sysAppService;

    @Autowired
    private SysTenantTrialMapper tenantTrialMapper;

    @Autowired
    private SysTenantMapper tenantMapper;

    @Autowired
    private SysTenantRegisterMapper tenantRegisterMapper;

    @Autowired
    private SysTenantDictConfMapper tenantDictConfMapper;

    @Autowired
    private SysEmployeeMapper employeeMapper;

    @Autowired
    private SysReponsibilityMapper reponsibilityMapper;

    @Autowired
    private SysEmpResponsiblityMapper empResponsiblityMapper;

    @Autowired
    private SysCaptchaService captchaService;

    @Autowired
    private SysSmsService smsService;

    @Autowired
    private SysLoginTokenService loginTokenService;

    @PostMapping(value = "/login")
    @Transactional(rollbackFor=Exception.class)
    @ApiOperation(value="登陆接口", notes="登陆接口" ,httpMethod="POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="username", value="用户名", dataType = "String", required=true ),
            @ApiImplicitParam(name="password", value="密码", dataType = "String", required=true ),
            @ApiImplicitParam(name="password", value="微信用户openid", dataType = "String", required=true )
    })
    @NotCheckToken
    public Map login(HttpServletRequest request,
            @RequestParam("username") String username,
                     @RequestParam("password") String password,
                     @RequestParam(name ="openId" ,required = false) String openid,
                     @RequestParam(required = false) Integer tenantId){

        Map result = new HashMap();
        if (tenantId == null) {
            //优先查找试用表
            boolean isTrialExpire = false;

            QueryWrapper<SysTenantTrial> tenantTrialQR = new QueryWrapper<>();
            tenantTrialQR.lambda().eq(SysTenantTrial::getPhone, username);
            SysTenantTrial tenantTrial = tenantTrialMapper.selectOne(tenantTrialQR);


            if (tenantTrial != null && tenantTrial.getStatus() == 2) {
                //有试用信息且已过期
                isTrialExpire = true;
            }

            if (isTrialExpire) {
                return MsgUtil.retMsgMap(MsgConstant.FAILED_RET, "体验账号已到期，请联系工作人员开通账号");
            }
            //直接全局查找手机号码对应的租户
            QueryWrapper<SysTenantRegister> tenantRegisterQR = new QueryWrapper<>();
            tenantRegisterQR.lambda().eq(SysTenantRegister::getPhone, username);
            SysTenantRegister tenantRegister = tenantRegisterMapper.selectOne(tenantRegisterQR);
            if (tenantRegister != null) {
                tenantId = tenantRegister.getTenantId();
            } else {
                //在所有租户中查找是否有此员工， 最新注册的租户在最先
                boolean isEmpExist = false;
                QueryWrapper<SysEmployee> employeeQR = new QueryWrapper<>();
                employeeQR.lambda().eq(SysEmployee::getPhone, username)
                        .orderByDesc(SysEmployee::getCreate_time);
                List<SysEmployee> employeeList = employeeMapper.selectList(employeeQR);
                if (employeeList != null && employeeList.size() > 0)
                    isEmpExist = true;

                if (!isEmpExist) {

                    return MsgUtil.retMsgMap(MsgConstant.FAILED_RET, "账号不存在");

                }
                SysEmployee employee = employeeList.get(0);
                tenantId = employee.getTenantId();

                if (employee.getStatus() != null && employee.getStatus().equals("2")) {

                    return MsgUtil.retMsgMap(MsgConstant.FAILED_RET, "此账号员工已经离职");
                }
                if (employee.getStatus() != null && employee.getStatus().equals("3")) {
                    return MsgUtil.retMsgMap(MsgConstant.FAILED_RET, "此账号已被禁用");
                }

                if (password != null && password.equals(employee.getLoginPwd())) {
                    SysLoginToken loginToken = loginTokenService.createTokenPortal(tenantId,
                            "2",
                            employee.getId(),
                            null,
                            null,
                            IpUtil.getIpAddr(request),
                            "pc");

                    result.put("employee", employee);
                    result.put("token", loginToken.getToken());
                    result.put("tenantId", tenantId);

                    return MsgUtil.retMap("loginInfo",result);
                }
                else {
                    return MsgUtil.retMsgMap(MsgConstant.FAILED_RET, "用户名密码错误");
                }
            }
        }
        return result;
    }




}
